package com.tsf;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.nio.charset.StandardCharsets;
// 新增颜色常量类的导入
import java.awt.Color;

public class StickyNote extends JFrame {
    private JTextArea textArea;
    private Point dragPoint;
    private boolean isDragging = false;
    private static int noteCount = 0;
    private static int openWindowCount = 0; // 新增：追踪当前打开的窗口数
    private JPanel mainPanel;

    private JTextField titleField;
    // 假设这些按钮已声明为成员变量：
    private JButton minimizeButton;
    private JButton closeButton;
    private JButton colorButton;
    private JButton pinButton; // 新增：固定按钮
    private boolean isPinned = true; // 新增：是否置顶
    // 新增成员变量
    private boolean movingWindowFromTitleBar = false;
    private Point dragWindowStartScreenFromTitleBar;
    private Point dragWindowStartLocationFromTitleBar;

    private MouseAdapter titleBarDragHandler = new MouseAdapter() {
        public void mousePressed(MouseEvent e) {
            movingWindowFromTitleBar = true;
            dragWindowStartScreenFromTitleBar = e.getLocationOnScreen();
            dragWindowStartLocationFromTitleBar = getLocation();
            // System.out.println("[头部拖动] mousePressed: dragWindowStartScreen=" + dragWindowStartScreenFromTitleBar + ", dragWindowStartLocation=" + dragWindowStartLocationFromTitleBar);
        }
        public void mouseReleased(MouseEvent e) {
            movingWindowFromTitleBar = false;
            // System.out.println("[头部拖动] mouseReleased");
        }
        public void mouseDragged(MouseEvent e) {
            if (movingWindowFromTitleBar) {
                Point p = e.getLocationOnScreen();
                int dx = p.x - dragWindowStartScreenFromTitleBar.x;
                int dy = p.y - dragWindowStartScreenFromTitleBar.y;
                setLocation(dragWindowStartLocationFromTitleBar.x + dx, dragWindowStartLocationFromTitleBar.y + dy);
                // System.out.println("[头部拖动] mouseDragged: p=" + p + ", dx=" + dx + ", dy=" + dy + ", newLocation=" + (dragWindowStartLocationFromTitleBar.x + dx) + "," + (dragWindowStartLocationFromTitleBar.y + dy));
            }
        }
        public void mouseMoved(MouseEvent e) {
            setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));
        }
    };
    // 删除托盘相关成员变量
    // 删除setupTray、minimizeToTray、restoreFromTray方法

    public StickyNote() {
        noteCount++;
        openWindowCount++; // 新增
        initializeUI();
        setupEventHandlers();
        // 只有主窗口（第一个实例）加载最近日志
        if (noteCount == 1) {
            loadLastSavedNote();
        }
        // 新增：窗口关闭时自动减少计数
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosed(WindowEvent e) {
                openWindowCount--;
            }
        });
        // 增加窗口激活监听，点击任务栏图标时自动显示窗口
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowActivated(WindowEvent e) {
                setVisible(true);
                setState(Frame.NORMAL);
                toFront();
            }
        });
    }

    private void loadLastSavedNote() {
        File notesDir = new File("notes");
        if (!notesDir.exists() || !notesDir.isDirectory()) return;
        File[] files = notesDir.listFiles((dir, name) -> name.endsWith(".txt"));
        if (files == null || files.length == 0) return;
        // 找到最后修改的文件
        File lastFile = files[0];
        for (File f : files) {
            if (f.lastModified() > lastFile.lastModified()) {
                lastFile = f;
            }
        }
        // 读取内容
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(lastFile), java.nio.charset.StandardCharsets.UTF_8))) {
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line).append("\n");
            }
            textArea.setText(sb.toString());
        } catch (IOException e) {
            // 忽略加载失败
        }
    }

    private void initializeUI() {
        setTitle("便利贴 " + noteCount);
        setSize(300, 250);
        setLocationRelativeTo(null);
        setUndecorated(true);
        setAlwaysOnTop(true);
        // setType(Type.UTILITY); // 注释掉，保证任务栏显示

        // 主内容面板，仍用BorderLayout
        mainPanel = new JPanel(new BorderLayout());
        mainPanel.setBackground(StickyNoteColors.MAIN_BG);
        mainPanel.setDoubleBuffered(true);

        JPanel titleBar = createTitleBar();
        mainPanel.add(titleBar, BorderLayout.NORTH);

        textArea = new JTextArea();
        // 设置字体为ttf/Microsoft YaHei Mono.ttf（英文），中文回退微软雅黑
        try {
            // 使用getResourceAsStream来加载jar内部的字体文件
            InputStream fontStream = getClass().getResourceAsStream("/ttf/Microsoft YaHei Mono.ttf");
            if (fontStream != null) {
                Font yaheiMono = Font.createFont(Font.TRUETYPE_FONT, fontStream).deriveFont(14f);
                textArea.setFont(yaheiMono);
                fontStream.close();
            } else {
                // 如果jar内没有找到，尝试从文件系统加载（开发环境）
                try {
                    Font yaheiMono = Font.createFont(Font.TRUETYPE_FONT, new File("ttf/Microsoft YaHei Mono.ttf")).deriveFont(14f);
                    textArea.setFont(yaheiMono);
                } catch (Exception e) {
                    textArea.setFont(new Font("Monospaced", Font.PLAIN, 14));
                }
            }
        } catch (Exception ex) {
            textArea.setFont(new Font("Monospaced", Font.PLAIN, 14));
        }
        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(false); // 关键：关闭按词断行，严格按字符断行
        textArea.setBackground(StickyNoteColors.DEFAULT);
        textArea.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        // 为textarea添加右键菜单
        textArea.setComponentPopupMenu(createTextAreaPopupMenu());

        JScrollPane scrollPane = new JScrollPane(textArea);
        scrollPane.setBorder(null);
        mainPanel.add(scrollPane, BorderLayout.CENTER);

        // 创建JLayeredPane作为根面板
        JLayeredPane layeredPane = new JLayeredPane();
        setContentPane(layeredPane);

        // mainPanel全铺满
        mainPanel.setBounds(0, 0, getWidth(), getHeight());
        layeredPane.add(mainPanel, JLayeredPane.DEFAULT_LAYER);

        // === 左下角和右下角拖动区域 ===
        final int CORNER_SIZE = 12;
        JPanel leftResizeCorner = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2 = (Graphics2D) g;
                g2.setColor(StickyNoteColors.LEFT_CORNER);
                int[] xPoints = {0, CORNER_SIZE, 0};
                int[] yPoints = {0, CORNER_SIZE, CORNER_SIZE};
                g2.fillPolygon(xPoints, yPoints, 3);
            }
        };
        leftResizeCorner.setOpaque(false);
        leftResizeCorner.setDoubleBuffered(true);
        leftResizeCorner.setCursor(Cursor.getPredefinedCursor(Cursor.SW_RESIZE_CURSOR));
        leftResizeCorner.setPreferredSize(new Dimension(CORNER_SIZE, CORNER_SIZE));
        leftResizeCorner.setBounds(0, getHeight() - CORNER_SIZE, CORNER_SIZE, CORNER_SIZE);
        // 专属resize逻辑
        leftResizeCorner.addMouseListener(new MouseAdapter() {
            Point dragStartScreen;
            Rectangle dragStartBounds;
            public void mousePressed(MouseEvent e) {
                dragStartScreen = e.getLocationOnScreen();
                dragStartBounds = getBounds();
            }
            public void mouseDragged(MouseEvent e) {
                Point p = e.getLocationOnScreen();
                int dx = p.x - dragStartScreen.x;
                int dy = p.y - dragStartScreen.y;
                int newX = dragStartBounds.x + dx;
                int newW = dragStartBounds.width - dx;
                int newH = dragStartBounds.height + dy;
                if (newW < 200) { newX = dragStartBounds.x + (dragStartBounds.width - 200); newW = 200; }
                if (newH < 150) newH = 150;
                setBounds(newX, dragStartBounds.y, newW, newH);
            }
        });
        leftResizeCorner.addMouseMotionListener(new MouseMotionAdapter() {
            public void mouseDragged(MouseEvent e) {
                ((MouseAdapter)leftResizeCorner.getMouseListeners()[0]).mouseDragged(e);
            }
        });
        layeredPane.add(leftResizeCorner, JLayeredPane.PALETTE_LAYER);

        JPanel rightResizeCorner = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2 = (Graphics2D) g;
                g2.setColor(StickyNoteColors.RIGHT_CORNER);
                int[] xPoints = {0, CORNER_SIZE, CORNER_SIZE};
                int[] yPoints = {CORNER_SIZE, CORNER_SIZE, 0};
                g2.fillPolygon(xPoints, yPoints, 3);
            }
        };
        rightResizeCorner.setOpaque(false);
        rightResizeCorner.setDoubleBuffered(true);
        rightResizeCorner.setCursor(Cursor.getPredefinedCursor(Cursor.SE_RESIZE_CURSOR));
        rightResizeCorner.setPreferredSize(new Dimension(CORNER_SIZE, CORNER_SIZE));
        rightResizeCorner.setBounds(getWidth() - CORNER_SIZE, getHeight() - CORNER_SIZE, CORNER_SIZE, CORNER_SIZE);
        // 专属resize逻辑
        rightResizeCorner.addMouseListener(new MouseAdapter() {
            Point dragStartScreen;
            Rectangle dragStartBounds;
            public void mousePressed(MouseEvent e) {
                dragStartScreen = e.getLocationOnScreen();
                dragStartBounds = getBounds();
            }
            public void mouseDragged(MouseEvent e) {
                Point p = e.getLocationOnScreen();
                int dx = p.x - dragStartScreen.x;
                int dy = p.y - dragStartScreen.y;
                int newW = dragStartBounds.width + dx;
                int newH = dragStartBounds.height + dy;
                if (newW < 200) newW = 200;
                if (newH < 150) newH = 150;
                setBounds(dragStartBounds.x, dragStartBounds.y, newW, newH);
            }
        });
        rightResizeCorner.addMouseMotionListener(new MouseMotionAdapter() {
            public void mouseDragged(MouseEvent e) {
                ((MouseAdapter)rightResizeCorner.getMouseListeners()[0]).mouseDragged(e);
            }
        });
        layeredPane.add(rightResizeCorner, JLayeredPane.PALETTE_LAYER);

        // 只在resize时同步角标位置
        addComponentListener(new ComponentAdapter() {
            @Override
            public void componentResized(ComponentEvent e) {
                mainPanel.setBounds(0, 0, getWidth(), getHeight());
                leftResizeCorner.setBounds(0, getHeight() - CORNER_SIZE, CORNER_SIZE, CORNER_SIZE);
                rightResizeCorner.setBounds(getWidth() - CORNER_SIZE, getHeight() - CORNER_SIZE, CORNER_SIZE, CORNER_SIZE);
            }
        });

        // 添加Ctrl+S快捷键保存
        KeyStroke ctrlS = KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_DOWN_MASK);
        textArea.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(ctrlS, "save");
        textArea.getActionMap().put("save", new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                saveNote();
            }
        });
        // 失去焦点时自动保存
        // 添加撤销管理器
        javax.swing.undo.UndoManager undoManager = new javax.swing.undo.UndoManager();
        textArea.getDocument().addUndoableEditListener(undoManager);
        // 添加Ctrl+Z快捷键撤销
        KeyStroke ctrlZ = KeyStroke.getKeyStroke(KeyEvent.VK_Z, InputEvent.CTRL_DOWN_MASK);
        textArea.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(ctrlZ, "undo");
        textArea.getActionMap().put("undo", new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (undoManager.canUndo()) {
                    undoManager.undo();
                }
            }
        });
        // 添加Tab键插入两个空格
        KeyStroke tabKey = KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0);
        textArea.getInputMap().put(tabKey, "insert-two-spaces");
        textArea.getActionMap().put("insert-two-spaces", new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                textArea.replaceSelection("  "); // 插入两个半角空格
            }
        });
    }

    private JPanel createTitleBar() {
        JPanel titleBar = new JPanel();
        titleBar.setLayout(new BoxLayout(titleBar, BoxLayout.X_AXIS));
        titleBar.setBackground(StickyNoteColors.TITLEBAR_BG);
        titleBar.setPreferredSize(new Dimension(300, 30));
        titleBar.setBorder(BorderFactory.createEmptyBorder(5, 10, 5, 10));

        // 新增菜单按钮
        JButton menuButton = new JButton();
        menuButton.setIcon(SticNoteUtil.getImageIcon("/img/gengduo.png", 18));
        menuButton.setPreferredSize(new Dimension(20, 20));
        menuButton.setBorderPainted(false);
        menuButton.setContentAreaFilled(false);
        menuButton.setFocusPainted(false);
        menuButton.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        menuButton.addActionListener(e -> showMenu(menuButton));

        // 新建便利贴按钮
        JButton addButton = new JButton();
        addButton.setIcon(SticNoteUtil.getImageIcon("/img/add.png", 18));
        addButton.setPreferredSize(new Dimension(20, 20));
        addButton.setBorderPainted(false);
        addButton.setContentAreaFilled(false);
        addButton.setFocusPainted(false);
        addButton.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        addButton.addActionListener(e -> new StickyNote().setVisible(true));

        JPanel leftPanel = new JPanel();
        leftPanel.setOpaque(false);
        leftPanel.setLayout(new BoxLayout(leftPanel, BoxLayout.X_AXIS));
        // leftPanel.setBorder(BorderFactory.createLineBorder(Color.RED, 1)); // 调试用红色边框
        leftPanel.add(menuButton);
        leftPanel.add(Box.createHorizontalStrut(5)); // 按钮间距
        leftPanel.add(addButton);
        leftPanel.setMinimumSize(new Dimension(55, 24)); // 强制固定宽度，增加宽度容纳两个按钮
        leftPanel.setPreferredSize(new Dimension(55, 24)); // 设置首选大小
        leftPanel.setMaximumSize(new Dimension(55, 24)); // 设置最大大小
        titleBar.add(leftPanel);
        titleBar.add(Box.createHorizontalStrut(10));

        // 可编辑标题
        titleField = new JTextField("便利贴 " + noteCount, 20);
        titleField.setFont(new Font("微软雅黑", Font.BOLD, 12));
        titleField.setBorder(null);
        titleField.setOpaque(false);
        titleField.setHorizontalAlignment(JTextField.LEFT);
        titleField.setForeground(Color.BLACK);
        titleField.setEditable(false);
        // titleField.setBorder(BorderFactory.createLineBorder(Color.GREEN, 1)); // 调试用绿色边框
        // 移除固定宽度，让titleField自动伸缩
        titleBar.add(titleField);
        titleBar.add(Box.createHorizontalStrut(5)); // 固定间距

        // 右侧按钮，先初始化再add
        colorButton = new JButton();
        colorButton.setIcon(SticNoteUtil.getImageIcon("/img/color.png", 18));
        colorButton.setPreferredSize(new Dimension(20, 20));
        colorButton.setBorderPainted(false);
        colorButton.setContentAreaFilled(false);
        colorButton.setFocusPainted(false);
        colorButton.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        colorButton.addActionListener(e -> changeColor());

        // 新增置顶按钮
        pinButton = new JButton();
        pinButton.setIcon(SticNoteUtil.getImageIcon(isPinned ? "/img/zhiding-yizhiding.png" : "/img/zhiding-weizhiding.png", 18));
        pinButton.setPreferredSize(new Dimension(20, 20));
        pinButton.setBorderPainted(false);
        pinButton.setContentAreaFilled(false);
        pinButton.setFocusPainted(false);
        pinButton.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        pinButton.setToolTipText(isPinned ? "取消固定到桌面" : "固定到桌面");
        pinButton.addActionListener(e -> {
            isPinned = !isPinned;
            setAlwaysOnTop(isPinned);
            pinButton.setToolTipText(isPinned ? "取消固定到桌面" : "固定到桌面");
            pinButton.setIcon(SticNoteUtil.getImageIcon(isPinned ? "/img/zhiding-yizhiding.png" : "/img/zhiding-weizhiding.png", 18));
        });

        minimizeButton = new JButton();
        minimizeButton.setIcon(SticNoteUtil.getImageIcon("/img/min.png", 18));
        minimizeButton.setPreferredSize(new Dimension(20, 20));
        minimizeButton.setBorderPainted(false);
        minimizeButton.setContentAreaFilled(false);
        minimizeButton.setFocusPainted(false);
        minimizeButton.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        minimizeButton.addActionListener(e -> setState(Frame.ICONIFIED));
        // 自动还原：监听窗口状态变化
        addWindowStateListener(new WindowStateListener() {
            @Override
            public void windowStateChanged(WindowEvent e) {
                // 不做任何隐藏操作，保持任务栏图标一直显示
            }
        });

        closeButton = new JButton();
        closeButton.setIcon(SticNoteUtil.getImageIcon("/img/close.png", 18));
        closeButton.setPreferredSize(new Dimension(20, 20));
        closeButton.setBorderPainted(false);
        closeButton.setContentAreaFilled(false);
        closeButton.setFocusPainted(false);
        closeButton.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        // 修改关闭按钮逻辑
        closeButton.addActionListener(e -> {
            if (openWindowCount > 1) {
                // 只关闭当前窗口
                dispose();
            } else {
                // 只剩一个窗口，退出程序
                System.exit(0);
            }
        });

        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.X_AXIS));
        buttonPanel.setOpaque(false);
        // buttonPanel.setBorder(BorderFactory.createLineBorder(Color.BLUE, 1)); // 调试用蓝色边框
        buttonPanel.add(pinButton); // 新增：先加pinButton
        buttonPanel.add(Box.createHorizontalStrut(5)); // 按钮间距
        buttonPanel.add(colorButton);
        buttonPanel.add(Box.createHorizontalStrut(5)); // 按钮间距
        buttonPanel.add(minimizeButton);
        buttonPanel.add(Box.createHorizontalStrut(5)); // 按钮间距
        buttonPanel.add(closeButton);
        buttonPanel.setMinimumSize(new Dimension(110, 24)); // 强制固定宽度
        buttonPanel.setPreferredSize(new Dimension(110, 24)); // 设置首选大小
        buttonPanel.setMaximumSize(new Dimension(110, 24)); // 设置最大大小
        titleBar.add(buttonPanel);

        // 绑定拖动事件和鼠标样式
        addUniqueMouseListenerAndMotionListener(titleBar, titleBarDragHandler, titleBarDragHandler);
        addUniqueMouseListenerAndMotionListener(titleField, titleBarDragHandler, titleBarDragHandler);
        titleField.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));
        // 双击进入编辑
        titleField.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 2) {
                    titleField.setEditable(true);
                    titleField.setBorder(BorderFactory.createLineBorder(StickyNoteColors.TITLEBAR_BG, 1));
                    titleBar.setBackground(StickyNoteColors.TITLEBAR_BG_EDIT);
                    // 编辑状态：不可拖动，鼠标为文本光标，光标到最后
                    titleField.removeMouseListener(titleBarDragHandler);
                    titleField.removeMouseMotionListener(titleBarDragHandler);
                    titleField.setCursor(Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR));
                    // 光标到最后
                    String text = titleField.getText();
                    titleField.setCaretPosition(text == null ? 0 : text.length());
                    titleField.requestFocus();
                }
            }
        });
        // 失去焦点或回车时退出编辑
        titleField.addActionListener(e -> {
            titleField.setEditable(false);
            titleField.setBorder(null);
            titleBar.setBackground(StickyNoteColors.TITLEBAR_BG);
            // 恢复拖动和MOVE_CURSOR（只add一次，退出编辑时只恢复样式）
            if (!hasTitleBarDragHandler(titleField)) {
                titleField.addMouseListener(titleBarDragHandler);
                titleField.addMouseMotionListener(titleBarDragHandler);
            }
            titleField.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));
        });
        titleField.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                titleField.setEditable(false);
                titleField.setBorder(null);
                titleBar.setBackground(StickyNoteColors.TITLEBAR_BG);
                // 恢复拖动和MOVE_CURSOR（只add一次，退出编辑时只恢复样式）
                if (!hasTitleBarDragHandler(titleField)) {
                    titleField.addMouseListener(titleBarDragHandler);
                    titleField.addMouseMotionListener(titleBarDragHandler);
                }
                titleField.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));
            }
        });
        return titleBar;
    }

    private void setupEventHandlers() {
        // 只给 mainPanel 加拖拽事件
        setupDragEvents(mainPanel);
        // 不再遍历给 titleBar 加 setupDragEvents，避免拖动冲突和抖动
    }

    private void setupDragEvents(JPanel panel) {
        panel.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                dragPoint = e.getPoint();
                isDragging = true;
            }

            @Override
            public void mouseReleased(MouseEvent e) {
                isDragging = false;
            }
        });

        panel.addMouseMotionListener(new MouseMotionAdapter() {
            @Override
            public void mouseDragged(MouseEvent e) {
                if (isDragging) {
                    Point currentLocation = getLocation();
                    setLocation(currentLocation.x + e.getX() - dragPoint.x,
                            currentLocation.y + e.getY() - dragPoint.y);
                }
            }
        });
    }

    private void saveNote() {
        try {
            String content = textArea.getText();
            if (!content.trim().isEmpty()) {
                File notesDir = new File("notes");
                if (!notesDir.exists()) {
                    notesDir.mkdir();
                }

                // 获取当前时间
                java.time.LocalDateTime now = java.time.LocalDateTime.now();
                String dateTime = String.format("%04d-%02d-%02d_%02d-%02d-%02d",
                    now.getYear(), now.getMonthValue(), now.getDayOfMonth(),
                    now.getHour(), now.getMinute(), now.getSecond());

                // 获取标题（去除特殊字符）
                String title = titleField.getText().trim();
                if (title.isEmpty()) title = "便利贴";
                // 替换文件名中的非法字符
                title = title.replaceAll("[\\/:*?\"<>|]", "_");

                String filename = title + "_" + dateTime + ".txt";
                File noteFile = new File(notesDir, filename);

                try (PrintWriter writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(noteFile), StandardCharsets.UTF_8))) {
                    writer.write(content);
                }
                // 不再弹出保存成功提示
            }
        } catch (IOException e) {
            JOptionPane.showMessageDialog(this, "保存失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void changeColor() {
        final Color[] colors = {
                StickyNoteColors.DEFAULT, // 默认灰色
                StickyNoteColors.BEIGE,   // 米色
                StickyNoteColors.PEACH,   // 桃色
                StickyNoteColors.SKYBLUE, // 天蓝
                StickyNoteColors.PINK,    // 粉红
                StickyNoteColors.GREEN    // 碧绿
        };

        final JPopupMenu colorMenu = new JPopupMenu();
        String[] colorNames = {"灰色", "米色", "桃色", "天蓝", "粉红", "碧绿"};
        for (int i = 0; i < colors.length; i++) {
            final Color color = colors[i];
            JMenuItem item = new JMenuItem(colorNames[i]);
            item.setBackground(color);
            item.setForeground(Color.BLACK);
            item.setPreferredSize(new Dimension(80, 30));
            item.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    setNoteColor(color);
                }
            });
            colorMenu.add(item);
        }

        // 让颜色菜单出现在颜色按钮正下方
        Point btnLoc = colorButton.getLocationOnScreen();
        Point winLoc = this.getLocationOnScreen();
        int x = btnLoc.x - winLoc.x;
        int y = btnLoc.y - winLoc.y + colorButton.getHeight();
        colorMenu.show(this, x, y);
    }

    private void setNoteColor(Color color) {
        getContentPane().setBackground(color);
        textArea.setBackground(color);
        repaint();
    }

    // 公共方法：为组件添加唯一的MouseListener和MouseMotionListener
    private void addUniqueMouseListenerAndMotionListener(Component comp, MouseListener ml, MouseMotionListener mml) {
        boolean hasML = false;
        for (MouseListener l : ((JComponent)comp).getMouseListeners()) {
            if (l == ml) { hasML = true; break; }
        }
        if (!hasML) ((JComponent)comp).addMouseListener(ml);
        boolean hasMML = false;
        for (MouseMotionListener l : ((JComponent)comp).getMouseMotionListeners()) {
            if (l == mml) { hasMML = true; break; }
        }
        if (!hasMML) ((JComponent)comp).addMouseMotionListener(mml);
    }

    // 在 StickyNote 类中增加辅助方法，判断监听器是否已存在
    private boolean hasTitleBarDragHandler(JTextField field) {
        for (MouseListener l : field.getMouseListeners()) {
            if (l == titleBarDragHandler) return true;
        }
        for (MouseMotionListener l : field.getMouseMotionListeners()) {
            if (l == titleBarDragHandler) return true;
        }
        return false;
    }

    private String extractContent(String text, String quoteType) {
        if (text == null || text.trim().isEmpty()) {
            JOptionPane.showMessageDialog(this, "无内容提取", "提示", JOptionPane.INFORMATION_MESSAGE);
            return null;
        }

        // 按逗号、换行、空格分割内容
        String[] items = text.split("[,，\\s\\n]+");
        StringBuilder result = new StringBuilder();

        for (String item : items) {
            item = item.trim();
            if (!item.isEmpty()) {
                if (result.length() > 0) {
                    result.append(",");
                }
                result.append(quoteType).append(item).append(quoteType);
            }
        }

        String finalResult = result.toString();
        if (finalResult.isEmpty()) {
            JOptionPane.showMessageDialog(this, "没有找到有效内容", "提示", JOptionPane.INFORMATION_MESSAGE);
            return null;
        }

        return finalResult;
    }

    private void copyToClipboard(String content, String message) {
        try {
            java.awt.datatransfer.StringSelection stringSelection = new java.awt.datatransfer.StringSelection(content);
            java.awt.datatransfer.Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
            clipboard.setContents(stringSelection, null);

            JOptionPane.showMessageDialog(this,
                message + "\n" + content,
                "提取成功",
                JOptionPane.INFORMATION_MESSAGE);
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this,
                "复制失败: " + ex.getMessage(),
                "错误",
                JOptionPane.ERROR_MESSAGE);
        }
    }

    private void showMenu(JButton menuButton) {
        JPopupMenu popupMenu = new JPopupMenu();

        JMenuItem extractItem1 = new JMenuItem("提取'内容'");
        extractItem1.addActionListener(e -> {
            // 提取单引号内容的功能 - 生成SQL IN参数
            String result = extractContent(textArea.getText(), "'");
            if (result != null) {
                copyToClipboard(result, "复制到剪贴板：");
            }
        });

        JMenuItem extractItem2 = new JMenuItem("提取\"内容\"");
        extractItem2.addActionListener(e -> {
            // 提取双引号内容的功能 - 生成API请求参数
            String result = extractContent(textArea.getText(), "\"");
            if (result != null) {
                copyToClipboard(result, "复制到剪贴板：");
            }
        });

        popupMenu.add(extractItem1);
        popupMenu.add(extractItem2);

        // 在菜单按钮下方显示弹出菜单
        popupMenu.show(menuButton, 0, menuButton.getHeight());
    }

    private JPopupMenu createTextAreaPopupMenu() {
        JPopupMenu popupMenu = new JPopupMenu();

        JMenuItem extractItem1 = new JMenuItem("提取'内容'");
        extractItem1.addActionListener(e -> {
            // 提取单引号内容的功能 - 生成SQL IN参数
            String result = extractContent(textArea.getSelectedText(), "'");
            if (result != null) {
                copyToClipboard(result, "复制到剪贴板：");
            }
        });

        JMenuItem extractItem2 = new JMenuItem("提取\"内容\"");
        extractItem2.addActionListener(e -> {
            // 提取双引号内容的功能 - 生成API请求参数
            String result = extractContent(textArea.getSelectedText(), "\"");
            if (result != null) {
                copyToClipboard(result, "复制到剪贴板：");
            }
        });

        popupMenu.add(extractItem1);
        popupMenu.add(extractItem2);

        return popupMenu;
    }

    public static void main(String[] args) {
        // 设置系统外观
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
            e.printStackTrace();
        }

        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                StickyNote note = new StickyNote();
                note.setVisible(true);
            }
        });
    }
}
